/*
*  command.c - parse msn commands
*  Copyright (c) 2005 Derek Ingrouville (dergro@users.sourceforge.net)
*
*  This program is free software; you can redistribute it and/or modify
*  it under the terms of the GNU General Public License as published by
*  the Free Software Foundation; either version 2 of the License, or
*  (at your option) any later version.
*
*  This program is distributed in the hope that it will be useful,
*  but WITHOUT ANY WARRANTY; without even the implied warranty of
*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*  GNU Library General Public License for more details.
*
*  You should have received a copy of the GNU General Public License
*  along with this program; if not, write to the Free Software
*  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/

#include <glib.h>
#include <string.h>

#include "command.h"

MsnCommand *
msn_command_format (const char *format, ...)
{
    va_list args;
    char *params = NULL;
    char *str = NULL;
    MsnCommand *cmd = NULL;

    g_return_val_if_fail (format != NULL, NULL);

    va_start (args, format);
    str = g_strdup_vprintf (format, args);
    va_end (args);

    if (str == NULL)
        return NULL;

    cmd = msn_command_from_string (str);

    return cmd;
}

MsnCommand *
msn_command_from_string (const char *str)
{
    MsnCommand *cmd = NULL;
    char *params_start = NULL;
    int count = 0;

    g_return_val_if_fail (str != NULL, NULL);
    g_return_val_if_fail (strlen (str) >= 3, NULL);

    cmd = g_new (MsnCommand, 1);
    cmd->command = g_strdup (str);
    params_start = strchr (str, ' ');

    if (params_start) {
        cmd->name = g_strndup (str, params_start - str);
        params_start++;
        cmd->params = g_strsplit (params_start, " ", 0);

        for (count = 1; cmd->params[count-1]; count++)
            cmd->param_count = count;
    }
    else {
        cmd->name = g_strdup (str);
        cmd->params =  NULL;
        cmd->param_count = 0;
    }

    cmd->ref_count = 0;

    return cmd;
}

/* TODO: if this is unneeded. why is it here? */
void
msn_command_ref (MsnCommand *cmd)
{
    g_return_if_fail (cmd != NULL);

	cmd->ref_count++;

	return;
}

/* TODO: if this is unneeded. why is it here? */
void
msn_command_unref (MsnCommand *cmd)
{
	g_return_if_fail (cmd != NULL);

    if (cmd->ref_count == 0)
        msn_command_free (cmd);

    cmd->ref_count--;

    return;
}

void
msn_command_free (MsnCommand *cmd)
{
    g_return_if_fail (cmd != NULL);

    if (cmd->ref_count > 0) {
        msn_command_unref (cmd);
        return;
    }

    if (cmd->name != NULL)
        g_free (cmd->name);

    if (cmd->params != NULL)
        g_strfreev (cmd->params);

    if (cmd->command != NULL)
        g_free (cmd->command);

    g_free (cmd);

    return;
}

